<template>
  <div class="activity-create-view">
    <!-- 页面头部 -->
    <div class="page-header glass-card">
      <div class="header-content">
        <div class="header-left">
          <button class="back-btn" @click="handleBack">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2"/>
            </svg>
            返回
          </button>
          <div class="header-text">
            <h1 class="page-title">{{ isEditing ? '编辑活动' : '创建活动' }}</h1>
            <p class="page-subtitle">组织精彩的家庭聚会和活动</p>
          </div>
        </div>

        <div class="header-actions">
          <button
            :disabled="isSaving"
            class="action-btn draft"
            @click="saveDraft"
          >
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2"/>
              <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2"/>
            </svg>
            保存草稿
          </button>

          <button
            :disabled="isSaving || !isFormValid"
            class="action-btn publish"
            @click="publishActivity"
          >
            <svg v-if="isSaving" class="loading-spinner" fill="none" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <path d="M12 6v6l4 2" stroke="currentColor" stroke-width="2"/>
            </svg>
            <svg v-else fill="none" viewBox="0 0 24 24">
              <path d="M12 19l7-7 3 3-7 7-3-3z" stroke="currentColor" stroke-width="2"/>
              <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z" stroke="currentColor" stroke-width="2"/>
              <path d="M2 2l7.586 7.586" stroke="currentColor" stroke-width="2"/>
              <circle cx="11" cy="11" r="2" stroke="currentColor" stroke-width="2"/>
            </svg>
            {{ isSaving ? '发布中...' : '发布活动' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 活动创建表单 -->
    <div class="create-section">
      <div class="create-container">

        <!-- 基本信息 -->
        <div class="form-section glass-card">
          <div class="section-header">
            <h3 class="section-title">
              <svg fill="none" viewBox="0 0 24 24">
                <rect height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="4"/>
                <line stroke="currentColor" stroke-width="2" x1="16" x2="16" y1="2" y2="6"/>
                <line stroke="currentColor" stroke-width="2" x1="8" x2="8" y1="2" y2="6"/>
                <line stroke="currentColor" stroke-width="2" x1="3" x2="21" y1="10" y2="10"/>
              </svg>
              基本信息
            </h3>
          </div>

          <div class="form-content">
            <div class="form-row">
              <div class="form-group full-width">
                <label class="form-label">活动标题 *</label>
                <input
                  v-model="activityForm.title"
                  class="form-input"
                  maxlength="100"
                  placeholder="为你的活动起个吸引人的标题..."
                  type="text"
                  @input="handleFormChange"
                />
                <div class="input-counter">{{ activityForm.title.length }}/100</div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group full-width">
                <label class="form-label">活动描述</label>
                <textarea
                  v-model="activityForm.description"
                  class="form-textarea"
                  maxlength="1000"
                  placeholder="详细描述你的活动内容、亮点和特色..."
                  rows="4"
                  @input="handleFormChange"
                ></textarea>
                <div class="input-counter">{{ activityForm.description.length }}/1000</div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">活动类型 *</label>
                <select v-model="activityForm.type" class="form-select" @change="handleFormChange">
                  <option value="">选择活动类型</option>
                  <option value="family">👨‍👩‍👧‍👦 家庭聚会</option>
                  <option value="dining">🍽️ 聚餐聚食</option>
                  <option value="travel">✈️ 旅行出游</option>
                  <option value="sports">🏃‍♂️ 运动健身</option>
                  <option value="entertainment">🎮 娱乐休闲</option>
                  <option value="learning">📚 学习培训</option>
                  <option value="celebration">🎉 庆祝活动</option>
                  <option value="outdoor">🌲 户外活动</option>
                  <option value="culture">🎭 文化艺术</option>
                  <option value="volunteer">🤝 志愿服务</option>
                  <option value="other">📝 其他活动</option>
                </select>
              </div>

              <div class="form-group">
                <label class="form-label">活动状态</label>
                <select v-model="activityForm.status" class="form-select" @change="handleFormChange">
                  <option value="draft">📝 草稿</option>
                  <option value="published">📢 已发布</option>
                  <option value="ongoing">🔄 进行中</option>
                  <option value="completed">✅ 已完成</option>
                  <option value="cancelled">❌ 已取消</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        <!-- 时间地点 -->
        <div class="form-section glass-card">
          <div class="section-header">
            <h3 class="section-title">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                <polyline points="12,6 12,12 16,14" stroke="currentColor" stroke-width="2"/>
              </svg>
              时间地点
            </h3>
          </div>

          <div class="form-content">
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">开始时间 *</label>
                <input
                  v-model="activityForm.startTime"
                  class="form-input"
                  type="datetime-local"
                  @change="handleFormChange"
                />
              </div>

              <div class="form-group">
                <label class="form-label">结束时间</label>
                <input
                  v-model="activityForm.endTime"
                  class="form-input"
                  type="datetime-local"
                  @change="handleFormChange"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">地点名称 *</label>
                <input
                  v-model="activityForm.locationName"
                  class="form-input"
                  maxlength="100"
                  placeholder="例如：家里、公园、餐厅等"
                  type="text"
                  @input="handleFormChange"
                />
              </div>

              <div class="form-group">
                <label class="form-label">详细地址</label>
                <input
                  v-model="activityForm.locationAddress"
                  class="form-input"
                  maxlength="200"
                  placeholder="具体地址（可选）"
                  type="text"
                  @input="handleFormChange"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group full-width">
                <label class="form-label">GPS坐标</label>
                <div class="location-input">
                  <input
                    v-model="activityForm.latitude"
                    class="form-input"
                    placeholder="纬度"
                    step="0.000001"
                    type="number"
                    @input="handleFormChange"
                  />
                  <input
                    v-model="activityForm.longitude"
                    class="form-input"
                    placeholder="经度"
                    step="0.000001"
                    type="number"
                    @input="handleFormChange"
                  />
                  <button class="location-btn" @click="getCurrentLocation">
                    <svg fill="none" viewBox="0 0 24 24">
                      <circle cx="12" cy="10" r="3" stroke="currentColor" stroke-width="2"/>
                      <path d="m8.21 13.89 3.79 2.11 3.79-2.11M12 2v3m6.36 1.64l-2.12 2.12M21 12h-3m-1.64 6.36l-2.12-2.12M12 21v-3m-6.36-1.64l2.12-2.12M3 12h3m1.64-6.36l2.12 2.12" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    获取当前位置
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 参与设置 -->
        <div class="form-section glass-card">
          <div class="section-header">
            <h3 class="section-title">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
                <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
                <path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" stroke="currentColor" stroke-width="2"/>
              </svg>
              参与设置
            </h3>
          </div>

          <div class="form-content">
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">最大参与人数</label>
                <input
                  v-model.number="activityForm.maxParticipants"
                  class="form-input"
                  max="1000"
                  min="0"
                  placeholder="0 表示不限制"
                  type="number"
                  @input="handleFormChange"
                />
              </div>

              <div class="form-group">
                <label class="form-label">人均预算</label>
                <div class="budget-input">
                  <input
                    v-model.number="activityForm.budgetPerPerson"
                    class="form-input"
                    min="0"
                    placeholder="0"
                    step="0.01"
                    type="number"
                    @input="handleFormChange"
                  />
                  <select v-model="activityForm.currency" class="currency-select">
                    <option value="CNY">¥ CNY</option>
                    <option value="USD">$ USD</option>
                    <option value="EUR">€ EUR</option>
                  </select>
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">报名截止时间</label>
                <input
                  v-model="activityForm.registrationDeadline"
                  class="form-input"
                  type="datetime-local"
                  @change="handleFormChange"
                />
              </div>

              <div class="form-group">
                <label class="form-label">活动可见性</label>
                <select v-model="activityForm.visibility" class="form-select" @change="handleFormChange">
                  <option value="public">🌍 公开</option>
                  <option value="family">👨‍👩‍👧‍👦 仅家庭成员</option>
                  <option value="friends">👥 朋友可见</option>
                  <option value="private">🔒 私密</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group full-width">
                <label class="form-label">参与要求</label>
                <textarea
                  v-model="activityForm.requirements"
                  class="form-textarea"
                  maxlength="500"
                  placeholder="参与此活动需要满足的条件或准备的物品..."
                  rows="3"
                  @input="handleFormChange"
                ></textarea>
                <div class="input-counter">{{ activityForm.requirements.length }}/500</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 邀请用户 -->
        <div class="form-section glass-card">
          <div class="section-header">
            <h3 class="section-title">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
                <circle cx="8.5" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
                <line stroke="currentColor" stroke-width="2" x1="20" x2="20" y1="8" y2="14"/>
                <line stroke="currentColor" stroke-width="2" x1="23" x2="17" y1="11" y2="11"/>
              </svg>
              邀请成员
            </h3>
          </div>

          <div class="form-content">
            <div class="invite-section">
              <div class="search-users">
                <input
                  v-model="userSearchQuery"
                  class="form-input"
                  placeholder="搜索并邀请家人朋友..."
                  type="text"
                  @input="searchUsers"
                />

                <div v-if="searchResults.length > 0" class="search-results">
                  <div
                    v-for="user in searchResults"
                    :key="user.id"
                    class="user-result"
                    @click="inviteUser(user)"
                  >
                    <div class="user-avatar">
                      <img v-if="user.avatar" :alt="user.name" :src="user.avatar" />
                      <div v-else class="avatar-placeholder">
                        {{ user.name.charAt(0) }}
                      </div>
                    </div>
                    <div class="user-info">
                      <div class="user-name">{{ user.name }}</div>
                      <div class="user-relation">{{ user.relation }}</div>
                    </div>
                    <button class="invite-btn">
                      <svg fill="none" viewBox="0 0 24 24">
                        <line stroke="currentColor" stroke-width="2" x1="12" x2="12" y1="5" y2="19"/>
                        <line stroke="currentColor" stroke-width="2" x1="5" x2="19" y1="12" y2="12"/>
                      </svg>
                    </button>
                  </div>
                </div>
              </div>

              <div v-if="invitedUsers.length > 0" class="invited-users">
                <h4 class="invited-title">已邀请成员 ({{ invitedUsers.length }})</h4>
                <div class="invited-list">
                  <div
                    v-for="user in invitedUsers"
                    :key="user.id"
                    class="invited-user"
                  >
                    <div class="user-avatar">
                      <img v-if="user.avatar" :alt="user.name" :src="user.avatar" />
                      <div v-else class="avatar-placeholder">
                        {{ user.name.charAt(0) }}
                      </div>
                    </div>
                    <div class="user-info">
                      <div class="user-name">{{ user.name }}</div>
                      <div class="user-relation">{{ user.relation }}</div>
                    </div>
                    <button class="remove-btn" @click="removeInvite(user.id)">
                      <svg fill="none" viewBox="0 0 24 24">
                        <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
                        <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 活动封面 -->
        <div class="form-section glass-card">
          <div class="section-header">
            <h3 class="section-title">
              <svg fill="none" viewBox="0 0 24 24">
                <rect height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="3"/>
                <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2"/>
                <polyline points="21,15 16,10 5,21" stroke="currentColor" stroke-width="2"/>
              </svg>
              活动封面
            </h3>
          </div>

          <div class="form-content">
            <div class="cover-upload">
              <div v-if="!activityForm.coverImage" class="upload-area" @click="selectCoverImage">
                <div class="upload-content">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z" stroke="currentColor" stroke-width="2"/>
                    <circle cx="12" cy="13" r="3" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  <h4>上传活动封面</h4>
                  <p>支持 JPG、PNG 格式，建议尺寸 1200x630</p>
                </div>
              </div>

              <div v-else class="cover-preview">
                <img :src="activityForm.coverImage" alt="活动封面" />
                <div class="cover-actions">
                  <button class="action-btn change" @click="selectCoverImage">
                    <svg fill="none" viewBox="0 0 24 24">
                      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2"/>
                      <path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    更换
                  </button>
                  <button class="action-btn remove" @click="removeCoverImage">
                    <svg fill="none" viewBox="0 0 24 24">
                      <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2"/>
                      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    移除
                  </button>
                </div>
              </div>

              <input
                ref="coverInputRef"
                accept="image/*"
                class="file-input"
                type="file"
                @change="handleCoverImageSelect"
              />
            </div>
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="form-section glass-card">
          <div class="section-header">
            <h3 class="section-title">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2"/>
                <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2"/>
                <line stroke="currentColor" stroke-width="2" x1="16" x2="8" y1="13" y2="13"/>
                <line stroke="currentColor" stroke-width="2" x1="16" x2="8" y1="17" y2="17"/>
                <polyline points="10,9 9,9 8,9" stroke="currentColor" stroke-width="2"/>
              </svg>
              备注信息
            </h3>
          </div>

          <div class="form-content">
            <div class="form-row">
              <div class="form-group full-width">
                <label class="form-label">活动备注</label>
                <textarea
                  v-model="activityForm.notes"
                  class="form-textarea"
                  maxlength="1000"
                  placeholder="其他需要说明的信息..."
                  rows="4"
                  @input="handleFormChange"
                ></textarea>
                <div class="input-counter">{{ activityForm.notes.length }}/1000</div>
              </div>
            </div>

            <div class="form-row">
              <div class="checkbox-group">
                <label class="checkbox-setting">
                  <input v-model="activityForm.allowComments" type="checkbox" @change="handleFormChange" />
                  <span class="checkbox-custom"></span>
                  <span class="checkbox-text">允许评论</span>
                </label>

                <label class="checkbox-setting">
                  <input v-model="activityForm.autoApprove" type="checkbox" @change="handleFormChange" />
                  <span class="checkbox-custom"></span>
                  <span class="checkbox-text">自动通过报名申请</span>
                </label>

                <label class="checkbox-setting">
                  <input v-model="activityForm.sendNotifications" type="checkbox" @change="handleFormChange" />
                  <span class="checkbox-custom"></span>
                  <span class="checkbox-text">发送活动通知</span>
                </label>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>

    <!-- 提示遮罩 -->
    <div v-if="showUnsavedWarning" class="modal-overlay">
      <div class="modal-dialog">
        <div class="modal-header">
          <h3>未保存的更改</h3>
        </div>
        <div class="modal-body">
          <p>您有未保存的更改，确定要离开吗？</p>
        </div>
        <div class="modal-footer">
          <button class="modal-btn secondary" @click="cancelLeave">取消</button>
          <button class="modal-btn primary" @click="confirmLeave">离开</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Notify } from '@opentiny/vue'

const router = useRouter()

interface ActivityForm {
  title: string
  description: string
  type: string
  status: string
  startTime: string
  endTime: string
  locationName: string
  locationAddress: string
  latitude: number | null
  longitude: number | null
  maxParticipants: number | null
  budgetPerPerson: number | null
  currency: string
  registrationDeadline: string
  visibility: string
  requirements: string
  notes: string
  coverImage: string
  allowComments: boolean
  autoApprove: boolean
  sendNotifications: boolean
}

interface User {
  id: number
  name: string
  avatar?: string
  relation: string
}

// 响应式数据
const isEditing = ref(false)
const isSaving = ref(false)
const showUnsavedWarning = ref(false)
const hasUnsavedChanges = ref(false)

const coverInputRef = ref<HTMLInputElement>()
const userSearchQuery = ref('')
const searchResults = ref<User[]>([])
const invitedUsers = ref<User[]>([])

const activityForm = ref<ActivityForm>({
  title: '',
  description: '',
  type: '',
  status: 'draft',
  startTime: '',
  endTime: '',
  locationName: '',
  locationAddress: '',
  latitude: null,
  longitude: null,
  maxParticipants: null,
  budgetPerPerson: null,
  currency: 'CNY',
  registrationDeadline: '',
  visibility: 'family',
  requirements: '',
  notes: '',
  coverImage: '',
  allowComments: true,
  autoApprove: true,
  sendNotifications: true
})

// 计算属性
const isFormValid = computed(() => {
  return activityForm.value.title.trim() !== '' &&
         activityForm.value.type !== '' &&
         activityForm.value.startTime !== '' &&
         activityForm.value.locationName.trim() !== ''
})

// 事件处理函数
const handleBack = () => {
  if (hasUnsavedChanges.value) {
    showUnsavedWarning.value = true
  } else {
    router.back()
  }
}

const handleFormChange = () => {
  hasUnsavedChanges.value = true
}

const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        activityForm.value.latitude = position.coords.latitude
        activityForm.value.longitude = position.coords.longitude
        handleFormChange()
        Notify({
          type: 'success',
          message: '位置获取成功',
          position: 'top-right'
        })
      },
      (error) => {
        console.error('Error getting location:', error)
        Notify({
          type: 'warning',
          message: '无法获取位置信息',
          position: 'top-right'
        })
      }
    )
  } else {
    Notify({
      type: 'warning',
      message: '浏览器不支持地理定位',
      position: 'top-right'
    })
  }
}

const searchUsers = () => {
  if (userSearchQuery.value.trim() === '') {
    searchResults.value = []
    return
  }

  // 模拟搜索用户
  const mockUsers: User[] = [
    { id: 1, name: '张小明', avatar: '', relation: '家庭成员' },
    { id: 2, name: '李小红', avatar: '', relation: '朋友' },
    { id: 3, name: '王大华', avatar: '', relation: '同事' },
    { id: 4, name: '刘小芳', avatar: '', relation: '邻居' }
  ]

  searchResults.value = mockUsers.filter(user =>
    user.name.includes(userSearchQuery.value) &&
    !invitedUsers.value.some(invited => invited.id === user.id)
  )
}

const inviteUser = (user: User) => {
  if (!invitedUsers.value.some(invited => invited.id === user.id)) {
    invitedUsers.value.push(user)
    searchResults.value = searchResults.value.filter(result => result.id !== user.id)
    userSearchQuery.value = ''
    handleFormChange()
  }
}

const removeInvite = (userId: number) => {
  invitedUsers.value = invitedUsers.value.filter(user => user.id !== userId)
  handleFormChange()
}

const selectCoverImage = () => {
  coverInputRef.value?.click()
}

const handleCoverImageSelect = (e: Event) => {
  const input = e.target as HTMLInputElement
  const file = input.files?.[0]

  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      Notify({
        type: 'warning',
        message: '请选择图片文件',
        position: 'top-right'
      })
      return
    }

    // 验证文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      Notify({
        type: 'warning',
        message: '图片文件不能超过5MB',
        position: 'top-right'
      })
      return
    }

    // 生成预览
    const reader = new FileReader()
    reader.onload = (e) => {
      activityForm.value.coverImage = e.target?.result as string
      handleFormChange()
    }
    reader.readAsDataURL(file)
  }
}

const removeCoverImage = () => {
  activityForm.value.coverImage = ''
  if (coverInputRef.value) {
    coverInputRef.value.value = ''
  }
  handleFormChange()
}

const saveDraft = async () => {
  if (isSaving.value) return

  try {
    isSaving.value = true

    // 模拟保存草稿
    await new Promise(resolve => setTimeout(resolve, 1500))

    hasUnsavedChanges.value = false

    Notify({
      type: 'success',
      message: '草稿保存成功',
      position: 'top-right'
    })

  } catch (error) {
    console.error('Save draft failed:', error)
    Notify({
      type: 'error',
      message: '保存草稿失败，请重试',
      position: 'top-right'
    })
  } finally {
    isSaving.value = false
  }
}

const publishActivity = async () => {
  if (isSaving.value || !isFormValid.value) return

  try {
    isSaving.value = true

    // 模拟发布活动
    await new Promise(resolve => setTimeout(resolve, 2000))

    Notify({
      type: 'success',
      message: '活动发布成功',
      position: 'top-right'
    })

    // 跳转到活动列表
    router.push('/activity')

  } catch (error) {
    console.error('Publish activity failed:', error)
    Notify({
      type: 'error',
      message: '发布失败，请重试',
      position: 'top-right'
    })
  } finally {
    isSaving.value = false
  }
}

// 离开确认
const confirmLeave = () => {
  showUnsavedWarning.value = false
  hasUnsavedChanges.value = false
  router.back()
}

const cancelLeave = () => {
  showUnsavedWarning.value = false
}

// 页面生命周期
onMounted(() => {
  // 设置默认开始时间为当前时间
  const now = new Date()
  now.setMinutes(Math.ceil(now.getMinutes() / 30) * 30) // 向上取整到最近的30分钟
  activityForm.value.startTime = now.toISOString().slice(0, 16)

  // 设置默认结束时间为开始时间后2小时
  const endTime = new Date(now.getTime() + 2 * 60 * 60 * 1000)
  activityForm.value.endTime = endTime.toISOString().slice(0, 16)

  // 监听页面离开
  window.addEventListener('beforeunload', (e) => {
    if (hasUnsavedChanges.value) {
      e.preventDefault()
      e.returnValue = ''
    }
  })
})

onUnmounted(() => {
  // 清理事件监听
})
</script>

<style lang="scss" scoped>
.activity-create-view {
  background: #f8fafc;
  min-height: 100vh;

  .page-header {
    background: white;
    border-bottom: 1px solid #e5e7eb;
    position: sticky;
    top: 0;
    z-index: 10;

    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem 2rem;

      .header-left {
        display: flex;
        align-items: center;
        gap: 1.5rem;

        .back-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.5rem 1rem;
          background: #f3f4f6;
          border: none;
          border-radius: 8px;
          color: #6b7280;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover {
            background: #e5e7eb;
            color: #374151;
          }

          svg {
            width: 16px;
            height: 16px;
          }
        }

        .header-text {
          .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 0.25rem 0;
          }

          .page-subtitle {
            color: #64748b;
            margin: 0;
            font-size: 0.9rem;
          }
        }
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 1rem;

        .action-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.75rem 1.5rem;
          border-radius: 8px;
          border: none;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s ease;

          svg {
            width: 16px;
            height: 16px;
          }

          &.draft {
            background: #f3f4f6;
            color: #374151;

            &:hover {
              background: #e5e7eb;
            }
          }

          &.publish {
            background: #3b82f6;
            color: white;

            &:hover:not(:disabled) {
              background: #2563eb;
            }

            &:disabled {
              opacity: 0.6;
              cursor: not-allowed;
            }
          }

          .loading-spinner {
            animation: spin 1s linear infinite;
          }
        }
      }
    }
  }

  .create-section {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;

    .create-container {
      display: flex;
      flex-direction: column;
      gap: 2rem;
    }
  }

  .form-section {
    padding: 2rem;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .section-header {
      margin-bottom: 1.5rem;

      .section-title {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        font-size: 1.25rem;
        font-weight: 600;
        color: #1e293b;
        margin: 0;

        svg {
          width: 20px;
          height: 20px;
          color: #3b82f6;
        }
      }
    }

    .form-content {
      .form-row {
        display: flex;
        gap: 1.5rem;
        margin-bottom: 1.5rem;

        &:last-child {
          margin-bottom: 0;
        }

        .form-group {
          flex: 1;
          position: relative;

          &.full-width {
            width: 100%;
          }

          .form-label {
            display: block;
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
          }

          .form-input,
          .form-select,
          .form-textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 0.9rem;
            background: white;
            transition: border-color 0.2s ease;

            &:focus {
              outline: none;
              border-color: #3b82f6;
              box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }

            &::placeholder {
              color: #9ca3af;
            }
          }

          .form-textarea {
            resize: vertical;
            min-height: 100px;
          }

          .input-counter {
            position: absolute;
            bottom: -1.25rem;
            right: 0;
            font-size: 0.75rem;
            color: #9ca3af;
          }
        }
      }
    }
  }

  .location-input {
    display: flex;
    gap: 0.75rem;
    align-items: center;

    .form-input {
      flex: 1;
    }

    .location-btn {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.75rem 1rem;
      background: #3b82f6;
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 0.85rem;
      font-weight: 500;
      transition: background 0.2s ease;

      &:hover {
        background: #2563eb;
      }

      svg {
        width: 16px;
        height: 16px;
      }
    }
  }

  .budget-input {
    display: flex;
    gap: 0.5rem;

    .form-input {
      flex: 1;
    }

    .currency-select {
      width: 100px;
      padding: 0.75rem;
      border: 1px solid #d1d5db;
      border-radius: 8px;
      background: white;
      font-size: 0.9rem;

      &:focus {
        outline: none;
        border-color: #3b82f6;
      }
    }
  }

  .invite-section {
    .search-users {
      position: relative;
      margin-bottom: 1.5rem;

      .search-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        z-index: 10;
        max-height: 200px;
        overflow-y: auto;

        .user-result {
          display: flex;
          align-items: center;
          gap: 0.75rem;
          padding: 0.75rem;
          cursor: pointer;
          transition: background 0.2s ease;

          &:hover {
            background: #f9fafb;
          }

          .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
            flex-shrink: 0;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            .avatar-placeholder {
              width: 100%;
              height: 100%;
              background: #e5e7eb;
              color: #6b7280;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: 600;
            }
          }

          .user-info {
            flex: 1;

            .user-name {
              font-weight: 500;
              color: #374151;
            }

            .user-relation {
              font-size: 0.8rem;
              color: #6b7280;
            }
          }

          .invite-btn {
            width: 32px;
            height: 32px;
            border: none;
            background: #3b82f6;
            color: white;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;

            svg {
              width: 16px;
              height: 16px;
            }
          }
        }
      }
    }

    .invited-users {
      .invited-title {
        font-size: 1rem;
        font-weight: 600;
        color: #374151;
        margin: 0 0 1rem 0;
      }

      .invited-list {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;

        .invited-user {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.5rem;
          background: #f0f9ff;
          border: 1px solid #e0f2fe;
          border-radius: 8px;

          .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            .avatar-placeholder {
              width: 100%;
              height: 100%;
              background: #e5e7eb;
              color: #6b7280;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: 600;
              font-size: 0.8rem;
            }
          }

          .user-info {
            .user-name {
              font-size: 0.85rem;
              font-weight: 500;
              color: #374151;
            }

            .user-relation {
              font-size: 0.7rem;
              color: #6b7280;
            }
          }

          .remove-btn {
            width: 24px;
            height: 24px;
            border: none;
            background: transparent;
            color: #ef4444;
            cursor: pointer;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s ease;

            &:hover {
              background: rgba(239, 68, 68, 0.1);
            }

            svg {
              width: 14px;
              height: 14px;
            }
          }
        }
      }
    }
  }

  .cover-upload {
    .upload-area {
      border: 2px dashed #d1d5db;
      border-radius: 12px;
      padding: 3rem 2rem;
      text-align: center;
      cursor: pointer;
      transition: border-color 0.2s ease;

      &:hover {
        border-color: #3b82f6;
      }

      .upload-content {
        svg {
          width: 48px;
          height: 48px;
          color: #9ca3af;
          margin-bottom: 1rem;
        }

        h4 {
          font-size: 1.1rem;
          font-weight: 600;
          color: #374151;
          margin: 0 0 0.5rem 0;
        }

        p {
          color: #6b7280;
          margin: 0;
          font-size: 0.9rem;
        }
      }
    }

    .cover-preview {
      position: relative;
      border-radius: 12px;
      overflow: hidden;

      img {
        width: 100%;
        height: 200px;
        object-fit: cover;
      }

      .cover-actions {
        position: absolute;
        top: 1rem;
        right: 1rem;
        display: flex;
        gap: 0.5rem;

        .action-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.5rem 1rem;
          border-radius: 6px;
          border: none;
          cursor: pointer;
          font-size: 0.85rem;
          font-weight: 500;
          transition: all 0.2s ease;

          svg {
            width: 14px;
            height: 14px;
          }

          &.change {
            background: rgba(59, 130, 246, 0.9);
            color: white;

            &:hover {
              background: rgba(37, 99, 235, 0.9);
            }
          }

          &.remove {
            background: rgba(239, 68, 68, 0.9);
            color: white;

            &:hover {
              background: rgba(220, 38, 38, 0.9);
            }
          }
        }
      }
    }

    .file-input {
      display: none;
    }
  }

  .checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;

    .checkbox-setting {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      cursor: pointer;

      input[type="checkbox"] {
        display: none;
      }

      .checkbox-custom {
        width: 18px;
        height: 18px;
        border: 2px solid #d1d5db;
        border-radius: 4px;
        position: relative;

        &::after {
          content: '✓';
          position: absolute;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 12px;
          font-weight: bold;
          opacity: 0;
          transition: opacity 0.2s ease;
        }
      }

      input:checked + .checkbox-custom {
        background: #3b82f6;
        border-color: #3b82f6;

        &::after {
          opacity: 1;
        }
      }

      .checkbox-text {
        font-size: 0.9rem;
        color: #374151;
      }
    }
  }

  .modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 40;

    .modal-dialog {
      background: white;
      border-radius: 12px;
      min-width: 400px;
      max-width: 90vw;

      .modal-header {
        padding: 1.5rem 1.5rem 1rem;

        h3 {
          margin: 0;
          color: #1e293b;
        }
      }

      .modal-body {
        padding: 0 1.5rem 1rem;

        p {
          margin: 0;
          color: #6b7280;
        }
      }

      .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        padding: 1rem 1.5rem 1.5rem;

        .modal-btn {
          padding: 0.5rem 1rem;
          border-radius: 6px;
          border: none;
          cursor: pointer;
          transition: background 0.2s ease;

          &.secondary {
            background: #f3f4f6;
            color: #374151;

            &:hover {
              background: #e5e7eb;
            }
          }

          &.primary {
            background: #ef4444;
            color: white;

            &:hover {
              background: #dc2626;
            }
          }
        }
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 1024px) {
  .activity-create-view {
    .create-section {
      padding: 1.5rem;
    }

    .form-section {
      padding: 1.5rem;
    }

    .form-row {
      flex-direction: column;
      gap: 1rem;
    }

    .location-input {
      flex-direction: column;

      .location-btn {
        width: 100%;
        justify-content: center;
      }
    }
  }
}

@media (max-width: 768px) {
  .activity-create-view {
    .page-header .header-content {
      flex-direction: column;
      gap: 1rem;
      padding: 1rem 1.5rem;

      .header-left {
        flex-direction: column;
        gap: 0.75rem;
        text-align: center;

        .back-btn {
          align-self: flex-start;
        }

        .header-text {
          .page-title {
            font-size: 1.25rem;
          }

          .page-subtitle {
            font-size: 0.85rem;
          }
        }
      }

      .header-actions {
        width: 100%;
        justify-content: center;
      }
    }

    .create-section {
      padding: 1rem;
    }

    .form-section {
      padding: 1rem;

      .section-header .section-title {
        font-size: 1.1rem;

        svg {
          width: 18px;
          height: 18px;
        }
      }
    }

    .cover-upload .upload-area {
      padding: 2rem 1rem;
    }
  }
}
</style>
